#pragma once

#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include <functional>
#include <cstring>
#include <unistd.h>
#include <cstdlib>
#include <cctype>
#include "err.hpp"

class ns_client
{
public:
    ns_client(std::string clientIp,uint16_t clientPort)
        :_clientIp(clientIp)
        ,_clientPort(clientPort)
    {}

    void init()
    {
        _sock = socket(AF_INET,SOCK_STREAM,0);
        if(_sock < 0)
        {
            std::cout << "creat socket fail" << std::endl;
            exit(SOCKETERR);
        }
    }

    void Start()
    {
        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = inet_addr(_clientIp.c_str());
        local.sin_port = htons(_clientPort);

        int cnt = 1;
        while(!connect(_sock,(struct sockaddr*)&local,sizeof(local)))
        {
            std::cout << "正在重新连接服务器,现在是第" << cnt++  << "次" << std::endl;
            if(cnt == 5)
            {
                break;
            }
        }
        if(cnt == 5)
        {
            std::cout << "服务器始终无法连接,请稍后再试" << std::endl;
            exit(CONNECTERR);
        }
        std::cout << "服务器连接成功" << std::endl;

        while(true)
        {
            std::cout << "请输入信息" << std::endl;
            std::string message;
            getline(std::cin,message);
            int n = write(_sock,message.c_str(),message.size());
            if(n < 0)
            {
                std::cout << "写入错误" << std::endl;
                exit(WRITEFAIL);
            }
            
            char buffer[1024];
            n = read(_sock,buffer,sizeof(buffer) - 1);
            if(n < 0)
            {
                std::cout << "读取错误" << std::endl;
                exit(WRITEFAIL);
            }
            std::cout << "服务器发来信息 " << buffer << std::endl; 
        }
    }

    ~ns_client()
    {}
private:
    int _sock;
    std::string _clientIp;
    uint16_t _clientPort;
};